package hebClustering.searchEngines;

import java.util.HashSet;
import java.util.Set;

import com.google.code.bing.search.client.BingSearchClient;
import com.google.code.bing.search.client.BingSearchClient.SearchRequestBuilder;
import com.google.code.bing.search.client.BingSearchServiceClientFactory;
import com.google.code.bing.search.schema.SearchResponse;
import com.google.code.bing.search.schema.SourceType;
import com.google.code.bing.search.schema.web.WebResult;

/**
 * Bing search engine. 
 * 
 */
public class Bing implements ISearchEngine{

	@Override
	public Set<WebsiteInformation> search(String query,int numOfResults) {
		Set<WebsiteInformation> URLSet = new HashSet<WebsiteInformation>();

		BingSearchServiceClientFactory factory = BingSearchServiceClientFactory.newInstance();
		BingSearchClient client = factory.createBingSearchClient();

		SearchRequestBuilder builder = client.newSearchRequestBuilder();
		builder.withAppId("4035308924D50F422728C0CF6B7F78D5960840C5");
		builder.withQuery(query);
		builder.withSourceType(SourceType.WEB);
		builder.withVersion("2.0");
		builder.withMarket("he-il");
		//		builder.withMarket("en-us");
		//		builder.withAdultOption(AdultOption.MODERATE);
		//		builder.withSearchOption(SearchOption.ENABLE_HIGHLIGHTING);

		long requestCount;
		for (long i = 0; i < numOfResults; i = i + 50){
			requestCount = numOfResults - i;
			if (requestCount > 50)
				requestCount = 50;
			
			builder.withWebRequestCount(requestCount);
			builder.withWebRequestOffset(i);
			//builder.withWebRequestSearchOption(WebSearchOption.DISABLE_HOST_COLLAPSING);
			//builder.withWebRequestSearchOption(WebSearchOption.DISABLE_QUERY_ALTERATIONS);
			SearchResponse response = client.search(builder.getResult());

			for (WebResult result : response.getWeb().getResults()) {
//				System.out.println(result.getTitle());
				WebsiteInformation info = new WebsiteInformation(result.getUrl(),result.getTitle(),result.getDescription());
				URLSet.add(info);
			}
		}

		return URLSet;
	}

}
